import React from "react";
import ReactDOM from "react-dom";
import { WeaTag, WeaLocaleProvider, WeaSelect } from "ecCom";
import { Popover } from "antd";
import * as Util from "../../util/Util";
import { taskTag } from "../../apis/task/taskMain";

const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;

const TagPopoverBoxCom = (props) => {
  let {
    checkedTags,
    visiableChange,
    removeCheckedTag,
    taglistPopoverVisible,
    isExpansion = false,
  } = props;
  let style = isExpansion
    ? {
        position: "relative",
        top: "-11px",
        left: "30px",
      }
    : {
        position: "relative",
        top: " 5px",
      };
  style.marginLeft = 5;
  return (
    <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@l410h0`}
      trigger="hover"
      overlayClassName={
        "wea-workrelate-taskedit-taskitem-taglist-popover-wrapper"
      }
      placement={"bottom"}
      onVisibleChange={(visible) => visiableChange(visible)}
      content={
        <div>
          {checkedTags.map((tag2, ti2) => {
            return (
              <div
                title={tag2.showname}
                className="wea-workrelate-taskedit-taskitem-taglist-popover-item"
              >
                <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@gkdiew@${tag2.key}`}
                  key={tag2.key}
                  id={tag2.key}
                  closable={true}
                  onClose={(e) =>
                    removeCheckedTag(e, {
                      ...tag2,
                    })
                  }
                  color={tag2.color}
                >
                  {tag2.showname}
                </WeaTag>
              </div>
            );
          })}
        </div>
      }
    >
      <i
        className={taglistPopoverVisible ? "icon-coms-down" : "icon-coms-right"}
        style={style}
      />
    </Popover>
  );
};

export default class TagSelectBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "", //已选择的TagIds
      options: [], // TagArry
      checkedTags: [], // 已选择的TagArry
      taglistPopoverVisible: false,
      isExpansion: false, //不足以展示三个标签时，直接放入popover
      ...props,
    };
  }

  componentWillMount() {
    this.getTagData();
  }
  componentDidMount() {
    let header =  document.getElementById("themeLayoutRoute");
    let w = 0;
    if(header){
        w = $("#themeLayoutRoute").offset().left || 0;
    }
    let curWidth = window.innerWidth-w;
    if (curWidth < 1535) {
      this.setState({ isExpansion: true });
    }
  }

  componentWillReceiveProps(newProps) {
    this.setState(
      {
        ...this.state,
        ...newProps,
      }
    );
  }

  addCheckedTag = (v) => {
    let idArry = v.split(",");
    let { options, onCallBack } = this.state;

    const checkedTagArry = options.filter((tag) => {
      return idArry.includes(tag.key + "");
    });
    this.setState({ checkedTags: checkedTagArry, value: v }, () => {
      onCallBack &&
        typeof onCallBack === "function" &&
        onCallBack(checkedTagArry);
    });
  };

  removeCheckedTag = (e, tag) => {
    e.preventDefault();
    e.stopPropagation();
    let { checkedTags, tags, onCallBack } = this.state;
    let newCheckedTags = checkedTags.filter((item) => {
      if (item.key != tag.key) {
        return true;
      }
    });
    let ckids = newCheckedTags.reduce((ids, elem) => {
      ids += elem.key + ",";
      return ids;
    }, "");
    this.setState(
      {
        value: ckids,
        checkedTags: newCheckedTags,
      },
      () => {
        onCallBack &&
          typeof onCallBack === "function" &&
          onCallBack(newCheckedTags);
      }
    );
  };

  getTagData = () => {
    taskTag({
      operate: "searchList",
      includeAdmin: "1",
    }).then((res) => {
      const { checkedTags = [] } = this.state;
      let datas = [];
      res.datas.forEach((d, i) => {
        let data = {
          id: d.id + "",
          key: d.id + "",
          showname: d.name,
          color: d.color,
        };
        data.selected = checkedTags.find((tag) => tag.id == d.id) || false;
        datas.push(data);
      });
      this.setState({
        options: datas,
      });
    });
  };

  render() {
    let {
      options,
      value,
      checkedTags,
      taglistPopoverVisible,
      isExpansion,
    } = this.state;
    return (
      <div className="wea-workrelate-tagFilter-wrapper" onClick={()=>{this.getTagData()}}>
        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@ofgyb2`}
          helpfulTip={getLabel("387467", "请选择标签")}
          multiple
          options={options}
          value={value}
          viewAttr={2}
          onChange={(v) => {
            this.addCheckedTag(v);
          }}
          dropdownStyle={{
            maxWidth: "300px"
          }}
        />
        {isExpansion && checkedTags.length > 0 ? (
          <TagPopoverBoxCom ecId={`${this && this.props && this.props.ecId || ''}_TagPopoverBoxCom@fqa26c`}
            checkedTags={checkedTags}
            taglistPopoverVisible={taglistPopoverVisible}
            removeCheckedTag={this.removeCheckedTag}
            visiableChange={(visiable) => {
              this.setState({ taglistPopoverVisible: visiable });
            }}
            isExpansion
          />
        ) : (
          <span className="wea-workrelate-taskedit-title-tags-wrapper">
            <span className="wea-workrelate-taskedit-title-tags-wrapper-abs">
              {checkedTags.map((tag, ti) => {
                const tagShowCount = 3; // 最多只显示3个标签
                if (ti < tagShowCount) {
                  return (
                    <span title={tag.showname}>
                      <WeaTag ecId={`${this && this.props && this.props.ecId || ''}_WeaTag@qv5nis@${tag.key}`}
                        key={tag.key}
                        id={tag.key}
                        closable={true}
                        onClose={(e) => this.removeCheckedTag(e, { ...tag })}
                        color={tag.color}
                      >
                        {tag.showname}
                      </WeaTag>
                    </span>
                  );
                } else if (ti === tagShowCount) {
                  return (
                    <TagPopoverBoxCom ecId={`${this && this.props && this.props.ecId || ''}_TagPopoverBoxCom@hgeyjb@boxcom`}
                      checkedTags={checkedTags}
                      taglistPopoverVisible={taglistPopoverVisible}
                      removeCheckedTag={this.removeCheckedTag}
                      visiableChange={(visiable) => {
                        this.setState({ taglistPopoverVisible: visiable });
                      }}
                    />
                  );
                }
              })}
            </span>
          </span>
        )}
      </div>
    );
  }
}
